{% extends 'index.html' %}

{% block page-title %}
镜像上传
{% endblock %}

{% block page-content %}
<style>
.sea {
    z-index: 9999;
}
</style>
<div class="row">

    <div class="col-lg-12">
        <div class="input-group col-lg-2 pull">
            <button class="btn btn-success" data-toggle="modal" data-target="#uploadModal">新建任务</button>
        </div>
        <div class="panel" >
            <div class="pannel-heading">
                <h3 class="panel-title">上传任务列表</h3>
            </div>
            <div class="pannel-body">
                <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>时间</th>
                                <th>IP</th>
                                <th>文件名</th>
                                <th>目录</th>
                                <th>状态</th>
                                <th>进度</th>
                                <th>操作</th>
                            </tr>
                        </thead>

                </table>
                <div class="pagination pull-left">

                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
	<div class="modal-dialog modal">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title">
					文件上传
				</h4>
			</div>
			<div class="modal-body">
                    <form class="form-horizontal" role="form" id="isoForm">
                        <div class="input-group">
                            <div class="input-group-addon">IP</div>
                            <div class="col-sm-12 sea">
                                <select id="IP" name="IP" class="selectpicker form-control"  data-live-search="true">
                                    <option value="" selected="true" disabled="true">请选择主机</option>
                                    {% for host in host_list %}
                                    <option value="{{ host }}">{{ host }}</option>
                                    {% endfor %}
                                 </select>
                            </div>
                        </div>
                        <div class="input-group">
                            <div class="input-group-addon">选择文件</div>
                            <div class="col-sm-12">
                                <input id="iso_file" name="iso_file" type="file" class="file"/>
                            </div>
                        </div>

                        <div class="input-group">
                            <div class="input-group-addon">文件路径</div>
                            <div class="col-sm-12">
                                <input type="text" class="form-control" name="path" id="path"/>
                            </div>
                        </div>

                    </form>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭
				</button>
				<button type="button" class="btn btn-primary" onclick="confirmForm()">
					上传
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>

{% endblock %}
{% block bottom-js %}
<script src="https://cdn.bootcss.com/moment.js/2.20.1/moment.min.js"></script>
<script>
var ws_list={};
var pause_list={};
window.onbeforeunload=function () {
    var len=$('table tr').length;
    for(var i=0;i<len;i++){
        if($('table tr:eq('+i+')').find('td:eq(5)').text()==='正在传输'){
            return "当前有文件在传输，确定离开吗？"
        }
    }
};

$(function () {
    $('#isoForm').bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            iso_file: {
                message: 'The iso_file is not valid',
                validators: {
                    notEmpty: {
                        message: '请选择上传镜像'
                    }
                }
            },
            IP: {
                message: 'The IP is not valid',
                validators: {
                    notEmpty: {
                        message: '请选择主机'
                    }
                }
            },
            path: {
                message: 'The path is not valid',
                validators: {
                    notEmpty: {
                        message: '请输入上传路径'
                    }
                }
            }
        }
    });
});
$('#iso_file').fileinput({
    language: "zh",
    allowedFileExtensions: ['iso','ISO','GHO','gho','zip','exe','apk'],
    showUpload: false,
    showRemove: false,
    showCaption: true, //是否显示标题
    dropZoneEnabled: false, //是否显示拖拽区域
    showPreview: false,
    showUploadedThumbs: false,
    maxFileSize:0,
    browseClass: "btn btn-primary",
    previewFileIcon: "<i class='glyphicon glyphicon-king'></i>"

});

function upload_iso() {
    var ip=$('#IP option:selected').val();
    var file_path=$('#iso_file').val();
    var filename=getFileName(file_path);
    var path=$('#path').val();
    var paragraph = 16384;
    var fileslist=$('#iso_file').prop('files');
    var file=fileslist[0];
    var startSize,endSize = 0;
    var i = 0; j = 0;
    var rows=$('table tr').length;
    var id="task"+rows;
    var current_time=moment().format('YYYY-MM-DD HH:mm:ss');
    ws_list[id]=new WebSocket('ws://'+ip+":10086/");
    pause_list[id]=0;
    var ws=ws_list[id];

    var flag=1;
    ws.onopen = function(evt) {
        console.log('连接已成功建立！');
        ws.send('{"file_name":"'+filename+'","size":'+file.size+',"path":"'+path+'"}');
        var html_ele="<tr id='"+id+"'><td>"+rows+"</td><td>"+current_time+"</td><td>"+ip+"</td><td>"+filename+"</td><td>"+path+"</td><td>正在传输</td><td>0%</td><td><button type='button' class='btn btn-primary btn-sm' onclick=\"pause('"+id+"')\">" +
            "暂停</button><button type='button' class='btn btn-primary btn-sm' onclick=\"cancel('"+id+"')\"'>取消</button></td></tr>";
        $('table').append(html_ele);
    };

    ws.onmessage = function(evt) {
        console.log(evt.data);
        if(evt.data === "ok") {
            if (pause_list[id] === 0) {
                if (endSize < file.size) {
                    startSize = endSize;
                    endSize += paragraph;
                    if (file.slice) {
                        var blob = file.slice(startSize, endSize);
                    }
                    var reader = new FileReader();
                    reader.readAsArrayBuffer(blob);
                    reader.onload = function loaded(evt) {
                        var ArrayBuffer = evt.target.result;
                        ws.send(ArrayBuffer);
                    };
                } else {
                    ws.send('md5');
                    $('#'+id+' td:eq(-3)').text('正在计算MD5值');
                }
                $('#' + id + ' td:eq(-2)').text((endSize * 100 / file.size).toFixed() + '%');
            }else{
                ws.send('pause');
            }
        } else if(evt.data === 'exist'){
            alert('文件已存在，请确认上传路径是否正确！');
            ws.send('end');
        }else{
            $('#'+id+' td:eq(-3)').text('MD5:'+evt.data);
            ws.send('end');
        }
    };

    ws.onclose = function(evt) {
        console.log('连接关闭.');
        console.log(endSize);
        console.log((endSize*100/file.size).toFixed());
        if ((endSize*100/file.size).toFixed()==='100'){
{#            $('#'+id+' td:eq(-3)').text('传输完成');#}
            $('#'+id+' td:eq(-1)').attr('style','background-color:green')
        }else{
{#            $('#'+id+' td:eq(-3)').text('传输异常');#}
            $('#'+id+' td:eq(-1)').attr('style','background-color:red')
        }
        $('#'+id+' td:eq(-1)').text('');
        if (flag===1){
            add_db(id);
        }


    };
    ws.onerror = function (evt) {
        console.log('服务连接错误！');
        alert('该服务器尚未部署镜像传输服务，请先部署！');
        flag=0;
    }
}
function getFileName(o){
    var pos=o.lastIndexOf("\\");
    return o.substring(pos+1);
}

function confirmForm() {
    $('#isoForm').data('bootstrapValidator').validate();//手动对表单进行校检
    if (!$('#isoForm').data('bootstrapValidator').isValid()) {//判断校检是否通过
        // alert("验证不通过");
        return;
    }else {
        $('#uploadModal').modal('hide');
        return upload_iso();
    }

}

function add_db(ele) {
    var html_ele=$('#'+ele);
    var date_time=html_ele.find('td:eq(1)').text();
    var ip=html_ele.find('td:eq(2)').text();
    var filename=html_ele.find('td:eq(3)').text();
    var directory=html_ele.find('td:eq(4)').text();
    var status=html_ele.find('td:eq(5)').text();
    var action='insert';
    $.ajax({
        url:'/iso/history/',
        type:'POST',
        data:{action:action,date_time:date_time,ip:ip,filename:filename,directory:directory,status:status},
        success:function (callback) {
            console.log(callback);
        }
    })
}


function pause(ele){
    var id=ele;
    $('#'+id+' td:eq(-1)').find('button').eq(0).text('继续上传');
    $('#'+id+' td:eq(-1)').find('button').eq(0).attr('onclick','start("'+id+'")');
    pause_list[id]=1;
}

function start(ele){
    var id=ele;
    $('#'+id+' td:eq(-1)').find('button').eq(0).text('暂停');
    $('#'+id+' td:eq(-1)').find('button').eq(0).attr('onclick','pause("'+id+'")');
    pause_list[id]=0;
    ws_list[id].send('start');
}

function cancel(ele) {
    var id=ele;
    ws_list[id].close();
}
</script>
{% endblock %}
